//
//  CFProgressHUDIndicatorView.m
//  CFProgressHUD
//
//  Created by 千域互联 on 2018/3/18.
//  Copyright © 2018年 千域互联. All rights reserved.
//

#import "CFProgressHUDIndicatorView.h"

@interface CFProgressHUDIndicatorView ()
{
    BOOL _accessibilityUpdateScheduled;
}
+ (void)runBlock:(void(^)(void))block;
@end

static void runOnNextRunLoop(void(^block)(void))
{
    [[NSRunLoop currentRunLoop] performSelector:@selector(runBlock:) target:[CFProgressHUDIndicatorView class] argument:(id)block order:0 modes:@[NSRunLoopCommonModes]];
}

@implementation CFProgressHUDIndicatorView

- (instancetype)initWithFrame:(CGRect)frame
{
    return [self init];
}
- (instancetype)init
{
    return [self initWithContentView:nil];
}
- (instancetype)initWithContentView:(UIView *)contentView
{
    self = [super initWithFrame:(contentView ? contentView.frame : CGRectMake(.0, .0, 50, 50))];
    if (self) {
        self.opaque = NO;
        self.backgroundColor = [UIColor clearColor];
        
        self.isAccessibilityElement = YES;
        [self setNeedsAccessibilityUpdate];
        
        if (contentView) {
            _contentView = contentView;
            [self addSubview:self.contentView];
        }
    }
    return self;
}

- (void)setUpForHUDStyle:(CFProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled{}

+ (void)runBlock:(void (^)(void))block
{
    if (block != nil) {
        block();
    }
}

- (void)setNeedsAccessibilityUpdate
{
    if (!_accessibilityUpdateScheduled) {
        _accessibilityUpdateScheduled = YES;
    }
    runOnNextRunLoop(^{
        [self updateAccessibilityIfNeeded];
    });
}
- (void)updateAccessibilityIfNeeded
{
    if (_accessibilityUpdateScheduled) {
        [self updateAccessibility];
        _accessibilityUpdateScheduled = NO;
    }
}
- (void)updateAccessibility
{
    self.accessibilityLabel = [NSLocalizedString(@"加载中……", ) stringByAppendingFormat:@" %.f %%",self.progress];
}

#pragma mark ----------------- Getter & Setter -----------------
- (void)setProgress:(float)progress
{
    [self setProgress:progress animated:NO];
}
- (void)setProgress:(float)progress animated:(BOOL)animated
{
    if (fequal(self.progress, progress)) return;
    
    _progress = progress;
    [self setNeedsAccessibilityUpdate];
}

@end
